package com.cloud.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSONObject;
import com.cloud.util.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.cloud.service.LoginService;
import com.cloud.util.CookieUtil;

@RestController
public class LoginController {
	private static Logger log = LoggerFactory.getLogger(LoginController.class);
	@Autowired
	private LoginService loginService;

	/*
	用户
	 */
	/**
	 * 用户登录
	 * @param params
	 * @param request
	 * @param response
	 * @return
	 */
	@PostMapping("/login")
	public R login(@RequestBody JSONObject params, HttpServletRequest request, HttpServletResponse response){
		params.put("isAdmin",false);
		return loginService.login(params,request,response);
	}

	/**
	 * 用户注册
	 * @param params
	 * @param request
	 * @return
	 */
	@PostMapping("/register")
	public R register(@RequestBody JSONObject params, HttpServletRequest request) {
		return loginService.register(params, request);
	}

	/**
	 * 用户退出
	 * @param request
	 * @param response
	 * @return
	 */
	@PostMapping("/logout")
	public R logout(@RequestBody JSONObject params, HttpServletRequest request,HttpServletResponse response) {
		CookieUtil.deleteCookie(request, response, "DSG_USER");
		CookieUtil.deleteCookie(request, response, "DSG_ADMIN");
		loginService.loginout(params);
		return R.ok();
	}

	/**
	 * 获取验证码
	 * @return
	 */
	@PostMapping("/code")
	public R code(@RequestBody JSONObject params) {
		return loginService.getCode(params.getString("phone"));
	}

	/*
	管理员
	 */

	@PostMapping("/admin/login")
	public R adminLogin(@RequestBody JSONObject params,HttpServletRequest request, HttpServletResponse response){
		params.put("isAdmin",true);
		return loginService.login(params,request,response);
	}
}
